<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.w3.org/1999/xhtml">
<head th:replace="back/include :: header">
</head>
<body>
<form class="layui-form" id="searchForm">
    <div class="layui-row" style="text-align: center">
        <div class="layui-col-md12" style="padding: 20px">
            权限名称：
            <div class="layui-inline">
                <input class="layui-input" name="roleName" id="roleName" autocomplete="off">
            </div>
            权限字符：
            <div class="layui-inline">
                <input class="layui-input" name="roleKey" id="roleKey" autocomplete="off">
            </div>
            角色状态：
            <div class="layui-inline">
                <select name="status" lay-filter="status" id="status">
                    <option value="" selected>全部</option>
                    <option value="0">正常</option>
                    <option value="1">停用</option>
                </select>
            </div>
            创建时间：
            <div class="layui-inline">
                <input type="text" class="layui-input" name="startTime" id="startTime" placeholder="开始时间"
                       onfocus="noInput(this)">
            </div>
            -
            <div class="layui-inline">
                <input type="text" class="layui-input" name="endTime" id="endTime" placeholder="截止时间"
                       onfocus="noInput(this)">
            </div>
            <div class="layui-inline" style="float:right;">
                <button shiro:hasPermission="system:role:list" type="button" class="layui-btn" data-type="reload" id="search">搜索</button>
                <button shiro:hasPermission="system:role:list" type="button" class="layui-btn layui-btn-primary" data-type="reload" id="clear">重置</button>
                <button shiro:hasPermission="system:role:add" type="button" class="layui-btn" data-type="reload" id="add"><i class="layui-icon">&#xe608;</i>新增
                </button>
            </div>
        </div>
    </div>
</form>
<table class="layui-hide" id="demoTable" lay-filter="tableFilter"></table>

<!--弹出框-->
<form class="layui-form layui-form-pane" id="sysRoleInfo" style="display:none;padding:40px;">
    <input type="hidden" name="roleId" id="_roleId">
    <div class="layui-form-item" style="padding-top: 10px">
        <label class="layui-form-label is-required">角色名称</label>
        <div class="layui-input-block">
            <input type="text" name="roleName" id="_roleName" lay-verify="required|roleName" placeholder="请输入角色名称" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label is-required">权限字符</label>
        <div class="layui-input-block">
            <input type="text" name="roleKey" id="_roleKey" lay-verify="required" placeholder="请输入权限字符" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label is-required">显示顺序</label>
        <div class="layui-input-block">
            <input type="text" name="roleSort" id="_roleSort" lay-verify="required|number"  placeholder="请输入显示顺序" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">状态</label>
        <div class="layui-input-block">
            <input type="checkbox" checked="" id="_status" name="status" lay-skin="switch" lay-text="启用|停用">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">备注</label>
        <div class="layui-input-block">
            <input type="text" name="remark" id="_remark" placeholder="请输入备注信息" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">菜单权限</label>
        <div class="layui-col-md6">
            <div id="menuTrees"></div>
        </div>

    </div>
</form>
<script type="text/javascript">
    layui.use(['laydate', 'laypage', 'layer', 'table', 'tree', 'util', 'form'], function () {
        let layer = layui.layer, //弹层
            table = layui.table, //表格
            laydate = layui.laydate, //元素操作
            form = layui.form,
            tree = layui.tree;
        //执行一个 table 实例
        table.render({
            elem: '#demoTable'
            , url: '/back/sysRole/list'
            , method: 'post'
            , contentType: 'application/json'
            , id: 'demoTable'
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.status, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.count, //解析数据长度
                    "data": res.data //解析数据列表
                };
            }
            , where: {}
            , response: {
                statusCode: 1 //规定成功的状态码，默认：0
            }
            , page: true //开启分页
            , cols: [
                [
                    /*{type:'checkbox'}*/
                    /*   ,{title: '序号', type:'numbers', align: 'center'}*/
                    {width: '6%', field: 'roleId', title: '角色编号', align: 'center'}
                    , {field: 'roleName', title: '角色名称', align: 'center'}
                    , {field: 'roleKey', title: '权限字符', align: 'center'}
                    , {field: 'roleSort', title: '显示顺序', align: 'center'}
                    , {field: 'status', title: '角色状态', align: 'center', templet: '#checkboxS'}
                    , {
                    field: 'createTime', title: '创建时间', align: 'center', templet: function (d) {
                        return layui.util.toDateString(d.createTime, "yyyy-MM-dd HH:mm:ss");
                    }
                }
                    , {width: '15%', title: '操作', align: 'center', toolbar: '#bar'}
                ]
            ]
        });
        //常规用法
        laydate.render({
            elem: '#startTime'
            , trigger: 'click'
        });
        laydate.render({
            elem: '#endTime'
            , trigger: 'click'
        });
        $("#add").bind("click", function () {
            $("#sysRoleInfo").clearForm();
            $("#_roleId").val("");
            openLayer('新建角色', '/back/sysRole/add');
        });
        /*ESC关闭弹窗*/
        $(document).ready(function () {
        }).keydown(
            function (e) {
                if (e.which === 27) {
                    layer.closeAll();
                }
            });
        $("#search").bind("click", function () {
            searchForm();
        });
        form.on('select(status)', function (data) {
            searchForm();
        });
        $("#clear").bind("click", function () {
            $("#searchForm").clearForm();
            searchForm();
        });
        form.on('switch(release)', function (obj) {
            let data = {roleId: obj.value, status: obj.elem.checked ? 0 : 1}
            saveData("/back/sysRole/stopUsing", data);
            layer.closeAll();
            searchForm();
        });

        form.on('submit(formDemo)', function (data) {
            return false;
        });
        table.on('tool(tableFilter)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            let data = obj.data; //获得当前行数据
            let layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            if (layEvent === 'edit') { //编辑
                getEditData(data['roleId']);
                openLayer('编辑管理员信息', '/back/sysRole/update', data['roleId']);
            } else if (layEvent === 'del') { //删除
                layer.confirm('确认要删除吗', {icon: 3, title: '信息删除确认'}, function (index) {
                    saveData("/back/sysRole/del", {roleId: data['roleId']})
                });
            } else if (layEvent === 'toAuthUser') {
                location.href = "/back/sysRole/toAuthUser?roleId=" + data['roleId'];
            }
        });
        form.verify({
            roleName: function(value, item){ //value：表单的值、item：表单的DOM对象
                if(!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)){
                    return '角色名不能有特殊字符';
                }
                if(/(^\_)|(\__)|(\_+$)/.test(value)){
                    return '角色名首尾不能出现下划线\'_\'';
                }
                if(/^\d+\d+\d$/.test(value)){
                    return '角色名不能全为数字';
                }
                if(value.length<2){
                    return '角色名不得少于两个字符';
                }
            }

            //我们既支持上述函数式的方式，也支持下述数组的形式
            //数组的两个值分别代表：[正则匹配、匹配不符时的提示文字]
            ,pass: [/^[\S]{6,12}$/,'密码必须6到12位，且不能出现空格']

        });

        function saveData(url, data) {
            $.ajax({
                type: "post",
                url: url,
                data: JSON.stringify(data),
                headers: {
                    'Content-Type': 'application/json;charset=utf-8'
                },
                dataType: 'json',
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    console.log(XMLHttpRequest.status + "," + XMLHttpRequest.readyState + ","
                        + textStatus + "," + errorThrown);
                },
                success: function (result) {
                    if (result["status"] == 1) {
                        layer.closeAll();
                        layer.msg(result["msg"]);
                        searchForm();
                    } else {
                        layer.alert(result["msg"]);
                    }

                }
            });
        }

        function getEditData(data) {
            $("#sysRoleInfo").clearForm();
            $.ajax({
                type: "post",
                url: "/back/sysRole/getById",
                data: JSON.stringify({"roleId": data}),
                headers: {
                    'Content-Type': 'application/json;charset=utf-8'
                },
                dataType: 'json',
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    console.log(XMLHttpRequest.status + "," + XMLHttpRequest.readyState + ","
                        + textStatus + "," + errorThrown);
                },
                success: function (result) {
                    if (result["status"] == 1) {
                        let data = result["data"];
                        $("#_roleId").val(data["roleId"]);
                        $("#_roleKey").val(data["roleKey"]);
                        $("#_roleName").val(data['roleName'])
                        $("#_roleSort").val(data["roleSort"]);
                        $("#_remark").val(data["remark"]);
                        if (data['status'] == 0) {
                            $("#_status").prop('checked', true);
                        } else {
                            $("#_status").removeAttr('checked');
                        }
                        form.render("checkbox");

                    } else {
                        layui.alert(result['msg']);
                    }
                }
            });
        }

        function openLayer(titleName, url, roleId) {
            layer.open({
                type: 1,
                area: ['800px', '800px'],
                title: titleName
                , content: $("#sysRoleInfo"),
                shade: 0.3,
                resize: false,
                moveType: 1,//可拖动
                moveOut: true,//可拖动移出
                shadeClose: true,//点击遮罩关闭弹窗
                btn: ['提交', '返回'],
                success: function (layero, index) {
                    layero.addClass('layui-form');
                    layero.find('.layui-layer-btn0 ').attr('lay-filter', 'formVerify')
                        .attr('lay-submit', '');
                    if(!roleId)
                        $("#_status").prop('checked', true);
                    form.render();
                    initTree(roleId);
                },
                yes: function (layero, index) {
                    form.on('submit(formVerify)', function (data) {
                        let param = getparams(data.field);
                        param.menuIds = getCheckedIds(tree.getChecked('demoId1'));
                        saveData(url, param);
                        return false;
                    });

                }
                ,
                btn2: function (index, layero) {
                    layer.closeAll();
                },
                cancel: function (layero, index) {
                    layer.closeAll();
                }
            });
        }

        function getparams(data) {
            let o = {};
            o.roleName = data.roleName?data.roleName:null;
            o.roleKey = data.roleKey?data.roleKey:null;
            o.roleSort = data.roleSort?data.roleSort:null;
            o.roleId = data.roleId?data.roleId:null;
            o.remark = data.remark?data.remark:null;
            o.status = data.status?0:1;
            return o;
        }

        function searchForm() {
            layui.use('table', function () {
                let roleName = $("#roleName").val();
                let roleKey = $("#roleKey").val();
                let status = $("#status").val();
                let startTime = $("#startTime").val();
                let endTime = $("#endTime").val();
                if (startTime != "" && endTime != "") {
                    if (startTime > endTime) {
                        layer.msg('时间起始不可大于时间截止！');
                        $("#endTime").val("");
                        return;
                    }
                }
                let table = layui.table;
                table.reload('demoTable', {
                    where: {
                        roleName: roleName, roleKey: roleKey,
                        status: status, startTime: startTime,
                        endTime: endTime
                    }
                    , page: {
                        curr: 1 //重新从第 1 页开始
                    }
                });
            });
        }


        function initTree(roleId) {
            $("#menuTrees").html("");
            $.ajax({
                url: "/back/sysRole/roleMenuTreeData",
                type: "get",
                data: {roleId: roleId},
                success: function (data) {
                    layui.use(["tree", "util"], function () {
                        tree.render({
                            elem: '#menuTrees'
                            , data: data
                            , showCheckbox: true  //是否显示复选框
                            , id: 'demoId1'
                            , isJump: false //是否允许点击节点时弹出新窗口跳转
                            ,
                        });
                    });
                }
            });
        }
    });//layui 组件结束
    function getCheckedIds(nodes) {
        let ids = [];
        getChecked(nodes);

        function getChecked(data) {
            $.each(data, function (index, value) {
                ids.push(value['id']);
                if (value['children']) {
                    getChecked(value['children']);
                }
            });
        }

        return ids;
    }

    //让时间插件无法选中 达到禁止手输的目的
    function noInput(dom) {
        $(dom).blur();
    }
</script>
<script type="text/html" id="bar">
    <a shiro:hasPermission="system:role:edit" class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a shiro:hasPermission="system:role:del" class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    <a shiro:hasPermission="system:role:edit" class="layui-btn layui-btn-normal layui-btn-xs" lay-event="toAuthUser">分配用户</a>
</script>
<script id="checkboxS" type="text/html">
    <!-- 这里的 checked 的状态只是演示 -->
    <input type="checkbox" value="{{d.roleId}}" lay-skin="switch" lay-text="开启|停用" lay-filter="release" {{ d.status== 0
           ? 'checked' : '' }}>
</script>
</body>
